-- ChessTableM
-- created by cheny3
-- 棋桌

module("ChessTableM", package.seeall);

local options = {};
local FETCH_NUM = 3;

local whenLeaveDungeon = nil;
local whenSummonDie = nil;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    options = {};

    local chess_table_options_CSV = get_chess_table_CSV();
    for i = 1, #chess_table_options_CSV do
        local row = chess_table_options_CSV[i];

        options[row.id] = row;
    end
end

-- 模块初始化操作
function init()
    loadCsv();

    EventMgr.removeAll("ChessTableM");

    -- 离开迷宫事件
    EventMgr.register("ChessTableM", event.LEAVE_DUNGEON, whenLeaveDungeon);

    -- 召唤兽死亡事件
    EventMgr.register("ChessTableM", event.SUMMON_DIE, whenSummonDie);
end

-- 离开迷宫回调
whenLeaveDungeon = function()
    -- TODO
end

-- 召唤兽死亡
whenSummonDie = function(para)
    local summon = para["summon"];

    -- 不在活动副本不管了
    if not ActivityDungeonM.isInActivityDungeon() then
        return;
    end

    -- 召唤兽的classId
    local summonId = summon.classId;

    -- 找一下是否是关注的召唤兽
    for _, info in pairs(options) do
        if info["special_summon"] == summonId then
            local limiStr = info["limit_str"];
            BuildingBonusM.addFieldStat(limiStr, 1);
            break;
        end
    end
end

-- 查询
function query(optionId, path)
    local m = options[optionId];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 抽取选项
function fetchOptions()
    -- 五抽三
    local ret = {};
    local ids = table.keys(options);

    for i = 1, FETCH_NUM do
        local rand = DungeonM.getRandSeed("chess_table_fetch");
        local index = rand % #ids + 1;   -- 客户端下标多1
        local id = ids[index];
        table.insert(ret, id);
        -- 从选项中去掉
        table.remove(ids, index);
    end

    -- 返回排序后结果
    table.sort(ret);
    return { ["options"] = ret };
end

-- 选择选项
function selectOption(pos, optionId)
     local grid = DungeonM.getGridByPos(pos);

    -- 如果不是棋桌
    if grid.type ~= GRID_TYPE_CHESS_TABLE or
        grid.state == GRID_STATE_DISABLE then
        trace("ChessTableM", "不是棋桌或已失效。");
        return false;
    end

    -- 改变状态
    grid:changeState(GRID_STATE_DISABLE);

    -- 抛出事件
    EventMgr.fire(event.CHESS_TABLE_DISABLE, {["pos"] = pos});

    return killDoSummon(pos, optionId);
end

-- 召唤宠物
function killDoSummon(chessPos, optionId)
    local info = query(optionId);

    -- 试图杀死的怪物
    local monsterId = info["monster"];
    local targetPos;
    if type(monsterId) == "number" then
        for pos = 1, GRID_SIZE do
            repeat
                local grid = DungeonM.getGridByPos(pos);
                local monster = grid.monster;

                -- 不是指定的怪物或者怪物已经死亡了
                if not grid:isOpened() or
                    not grid:isMonster() or
                    not monster or
                    monster:query("base_class_id") ~= monsterId or
                    monster:isDead() then
                    break;
                end

                -- 修正伤害值
                local damage = monster:getHp();

                CombatM.doDamage(ME.user, monster, damage);

                -- SUMMON位置
                targetPos = pos;

                if grid.has_key or grid.bonus then
                    -- 有钥匙/奖励，附近选一个
                    targetPos = SummonM.findSummonPos(targetPos);
                end
            until true;

            if targetPos then
                -- 干掉一个就可以了
                break;
            end
        end
    end

    -- 召唤兽位置
    local para = {};
    if type(targetPos) == "number" then
        para["pos"] = targetPos;
    else
        para["pos"] = chessPos;
    end

    -- 清除玩家负面状态
    if info["args"]["clear_debuff"] and info["args"]["clear_debuff"] == 1 then
        -- 清空负面状态
        CombatStatusM.clearStatusByType(ME.user, COM_STATUS_DEBUFF);
        CombatStatusM.clearStatusByType(ME.user, COM_STATUS_DAMAGE);
        -- 清空debuff
        PropM.deleteProp(ME.user, "debuff");
    end

    -- 召唤兽信息
    local summonId = info["summon"];
    local limitNum = info["limit_times"];
    local specialRate = info["special_rate"];
    local limiStr = info["limit_str"];

    -- 有小概率出现钻石宠物
    local rand = DungeonM.getRandSeed("special_chess_summon");
    if rand % 1000 <= specialRate
        and BuildingBonusM.getFieldStat(limiStr) < limitNum then
        summonId = info["special_summon"];
        -- 策划需求：等到召唤兽死亡才标记
        -- BuildingBonusM.addFieldStat(limiStr, 1);
    end

    return SummonM.doSummon(summonId, para);
end